<template>
	<view class="ys">
		<button class="avatar-wrapper" @click="changeImg">
			<image :src="avatarUrl || '/static/0.png'" mode="" />
		</button>
		<form>
			<view class="inputli">
				<text>昵称</text>
				<input v-model="name" type="nickname" name="nickname" class="weui-input" />
			</view>
			<button class="sub" type="primary" @click="save">保存昵称</button>
		</form>
	</view>
</template>

<script>
	import {
		userIndex,
		changeNickName
	} from "@/api/api.js"
	export default {
		data() {
			return {
				avatarUrl: '',
				name: ''
			}
		},
		onLoad() {
			this.userIndex()
		},
		methods: {
			userIndex() {
				userIndex().then(res => {
					this.name = res.data.nickName
					this.avatarUrl = res.data.avatar_path
				})
			},
			chooseavatar(e) {
				console.log(e);
			},
			changeImg() {
				let that = this
				uni.chooseImage({
					count: 1,
					success: function(res) {
						uni.getImageInfo({
							src: res.tempFilePaths[0],
							success: (res1) => {
								console.log(res1);
								uni.uploadFile({
									url: that.$config.requestUrl +
										'/common/upload',
									methods: 'post',
									header: {
										'token': uni.getStorageSync('token')
									},
									name: 'UploadFile',
									fileType: 'image',
									filePath: res1.path,
									formData: {
										avatar: true,
										accept: 'image',
									},
									success: (res2) => {
										let res3 = JSON.parse(res2.data)
										if (res3.code == 0) {
											uni.showToast({
												title: '上传成功',
												icon: "none"
											})
											that.avatarUrl = res3.data.path
										} else {
											uni.$showMsg(res.msg)
										}
									}
								})
							}
						});
					}
				});
			},
			save() {
				changeNickName({
					nickName: this.name
				}).then(res => {
					uni.showToast({
						title: res.msg,
						icon: "none"
					})
					if (res.status == 1) {
						setTimeout(() => {
							uni.navigateBack()
						}, 500)
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	image {
		width: 80px;
		height: 80px;
		border-radius: 5px;
	}

	button {
		background-color: #8E060A;
		padding: 20px 0;
	}

	page {
		background-color: #fff;
	}

	.avatar-wrapper {
		border-radius: 0;
		border: 0;
		line-height: unset;
	}

	.inputli {
		display: flex;
		align-items: center;
		border-top: 1px solid #ddd;
		border-bottom: 1px solid #ddd;
		padding: 10px 10%;
		font-size: 14px;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.inputli input {
		width: 80%;
	}

	.sub {
		padding: 0;
		margin: 50px auto;
		width: 40%;
		font-size: 14px;
	}
</style>